import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:crypto/crypto.dart';
import 'dart:convert';
import '../models/user.dart';
import 'database_service.dart';

class AuthService extends ChangeNotifier {
  final DatabaseService _databaseService;
  User? _currentUser;
  bool _isLoggedIn = false;

  AuthService(this._databaseService) {
    _loadUserFromStorage();
  }

  User? get currentUser => _currentUser;
  bool get isLoggedIn => _isLoggedIn;

  Future<void> _loadUserFromStorage() async {
    final prefs = await SharedPreferences.getInstance();
    final userId = prefs.getInt('user_id');
    
    if (userId != null) {
      _currentUser = await _databaseService.getUserById(userId);
      if (_currentUser != null) {
        _isLoggedIn = true;
        notifyListeners();
      }
    }
  }

  Future<bool> register(String username, String email, String password) async {
    try {
      // Check if user already exists
      final existingUserByEmail = await _databaseService.getUserByEmail(email);
      if (existingUserByEmail != null) {
        throw Exception('用户邮箱已存在');
      }

      final existingUserByUsername = await _databaseService.getUserByUsername(username);
      if (existingUserByUsername != null) {
        throw Exception('用户名已存在');
      }

      // Hash password
      final hashedPassword = _hashPassword(password);

      // Create new user
      final user = User(
        username: username,
        email: email,
        password: hashedPassword,
        createdAt: DateTime.now(),
      );

      final userId = await _databaseService.insertUser(user);
      _currentUser = user.copyWith(id: userId);
      _isLoggedIn = true;

      // Save to shared preferences
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt('user_id', userId);

      notifyListeners();
      return true;
    } catch (e) {
      debugPrint('Registration error: $e');
      return false;
    }
  }

  Future<bool> login(String emailOrUsername, String password) async {
    try {
      User? user;
      
      // Try to find user by email first, then by username
      if (emailOrUsername.contains('@')) {
        user = await _databaseService.getUserByEmail(emailOrUsername);
      } else {
        user = await _databaseService.getUserByUsername(emailOrUsername);
      }

      if (user == null) {
        throw Exception('用户不存在');
      }

      // Verify password
      final hashedPassword = _hashPassword(password);
      if (user.password != hashedPassword) {
        throw Exception('密码错误');
      }

      _currentUser = user;
      _isLoggedIn = true;

      // Save to shared preferences
      final prefs = await SharedPreferences.getInstance();
      await prefs.setInt('user_id', user.id!);

      notifyListeners();
      return true;
    } catch (e) {
      debugPrint('Login error: $e');
      return false;
    }
  }

  Future<void> logout() async {
    _currentUser = null;
    _isLoggedIn = false;

    // Clear shared preferences
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('user_id');

    notifyListeners();
  }

  String _hashPassword(String password) {
    final bytes = utf8.encode(password);
    final digest = sha256.convert(bytes);
    return digest.toString();
  }

  bool validateEmail(String email) {
    return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  }

  bool validatePassword(String password) {
    return password.length >= 6;
  }

  bool validateUsername(String username) {
    return RegExp(r'^[a-zA-Z0-9_]{3,20}$').hasMatch(username);
  }
}